package com.qf.listenner;

import com.qf.Constant.RabbitMqConstant;
import com.qf.entity.Goods;
import com.rabbitmq.client.Channel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 你的名字
 * @Date: 2021/07/13/21:24
 * @Description:
 */
@Component
@Slf4j
public class GoodsListenner {
    @Autowired
private Configuration configuration;
    private String path;
    private Template template;

    @PostConstruct
    public void initPath() throws IOException {
        File file = ResourceUtils.getFile("shop-11-iterm\\src\\main\\resources\\templates");
        path= file.getAbsolutePath();
        //准备模板
         template = configuration.getTemplate("goodsIterm.ftl");
    }
    @RabbitListener(queues = RabbitMqConstant.GOODS_ITERM_QUEUE)
    public void addGoodsToEs(Goods goods , Channel channel, Message message) throws IOException {
        try {
            Map<String,Object> map=new HashMap<>();
            map.put("gname",goods.getGname());

            map.put("gprice",goods.getGprice());
            map.put("gpngList",goods.getGpng().split("\\|"));
            template.process(map,new FileWriter(path + File.separator + goods.getId() + ".html"));
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        }

    }
}
